package com.lanou.utp.service.serviceImpl;

import com.lanou.utp.entity.LoginUser;
import com.lanou.utp.entity.ValidateDetails;
import com.lanou.utp.mapper.LoginMapper;
import com.lanou.utp.service.LoginService;
import com.lanou.utp.utils.PasswordManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

@Service("loginService")
public class LoginServiceImpl implements LoginService {

    @Resource
    private LoginMapper loginMapper;

    @Resource
    private PasswordManager passwordManager;

    @Override
    @Transactional
    public ValidateDetails validateUser(LoginUser user) {

        // 将用户密码加密之后替换掉原本密码
        String encryptPwd = passwordManager.encryptPassword(user.getPassword());
        System.out.println("encryptPwd = " + encryptPwd);
        user.setPassword(encryptPwd);

        ValidateDetails validateDetails = new ValidateDetails();

        // 判断是不是管理员
        if (!(loginMapper.isAdmin(user) == null)) {
            validateDetails.setId(loginMapper.getAdminId(user));
            validateDetails.setName(user.getName());
            validateDetails.setPassword(user.getPassword());
            validateDetails.setVerified(true);
            validateDetails.setPosition(0);
            return validateDetails;
        }

        // 判断是哪种途径登录的
        if (!(loginMapper.loginByNumber(user) == null)) {

            validateDetails.setChannel(0);
            validateDetails.setVerified(true);

            // 判断是管理员还是教师还是学生登录
            if (!(loginMapper.number_isTeacher(user) == null)) {
                validateDetails.setId(loginMapper.getIdByNumber(user));
                validateDetails.setPosition(1);
            } else if (!(loginMapper.number_isStudent(user) == null)) {
                validateDetails.setId(loginMapper.getIdByNumber(user));
                validateDetails.setPosition(2);
            }

        } else if (!(loginMapper.loginByTelephone(user) == null)) {

            validateDetails.setChannel(1);
            validateDetails.setVerified(true);

            if (!(loginMapper.telephone_isTeacher(user) == null)) {
                validateDetails.setId(loginMapper.getIdByTelephone(user));
                validateDetails.setPosition(1);
            } else if (!(loginMapper.telephone_isStudent(user) == null)) {
                validateDetails.setId(loginMapper.getIdByTelephone(user));
                validateDetails.setPosition(2);
            }

        } else {
            validateDetails.setVerified(false);
        }

        String name = user.getName();
        String password = user.getPassword();

        validateDetails.setName(name);
        validateDetails.setPassword(password);

        // 返回用户数据
        return validateDetails;

    }
}
